import XLSX from "xlsx";

export function uploadExcel(files,block){
        let list = [];
        if (!files) {
          //如果没有文件
          return false;
        } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
          this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
          return false;
        }
        const fileReader = new FileReader();

        fileReader.onload = (ev) => {
          try {
            const data = ev.target.result;
            const workbook = XLSX.read(data, {
              type: "binary",
            });
            // if (workbook.SheetNames.length >= 1) {
              // this.$message({
              //   message: "导入数据表格成功",
              //   showClose: true,
              //   type: "success",
              // });
            // }
            const wsname = workbook.SheetNames[0]; //取第一张表
            const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
            // that.outputs = []; //清空接收数据
            for (var i = 0; i < ws.length; i++) {
              var sheetData = {
                // 键名为绑定 el 表格的关键字，值则是 ws[i][对应表头名]
                // index:ws[i]["序号"],
                userId: ws[i]["CP"],
                num: ws[i]["抽奖次数"],
                remark: formatDate(ws[i]["说明"], '/') // 2016-9-5
              };
              list.push(sheetData);
            }
            return block(list);
          } catch (e) {
            return false;
          }
        };
        // 如果为原生 input 则应是 files[0]
        fileReader.readAsBinaryString(files.raw);
      }


      function formatDate(numb, format) {
        if(typeof(numb)=='string' ){
          return numb
        }
        const time = new Date((numb - 1) * 24 * 3600000 + 1)
        time.setYear(time.getFullYear() - 70)
        const year = time.getFullYear() + ''
        const month = time.getMonth() + 1 + ''
        const date = time.getDate() - 1 + ''
        if (format && format.length === 1) {
          return year + format + month + format + date
        }
        return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
      }
